<?php
function outputJson($code, $msg = '', $content = '')
{
    $content = ($content == '') ? (object)null : $content;
    $data['code'] = $code;
    $data['msg'] = $msg;
    $data['data'] = replace_arr($content);
    return json_encode($data);
}


/**
 * 替换数组内 特殊字符
 * @param $array
 * @return array
 */
function replace_arr (&$array){
    if(is_array($array)){
        foreach ($array as $k=>$v){
            if(is_object($v)){
                try{
                    $obj = (new \app\index\model\CityModel($array[$k]));
                    if(!isset($obj['data'])){
                        $_arr = (new \think\Collection($array[$k]))->toArray();
                        $array[$k] = $_arr;
                    }else{
                        $array[$k] = $obj['data'];
                    }
                }catch (\Exception $e){
                    $array[$k] = $v;
                }
            }
            if(is_array($array[$k])){
                replace_arr ($array[$k]);
            }else{
                if ($v === null || $v === '0000-00-00' || $v === '0000-00-00 00:00:00' || $v === '0100-01-01' || $v === '0100-01-01 00:00:00'
                    ){ // || $v === '0.00' || $v === 0.00
                    $array[$k] = '';
                }
            }
        }
    }
    return $array;
}

function get_page($param)
{
    $param['page'] = isset($param['page']) && (int)$param['page'] > 0 ? (int)$param['page'] : 0;
    $param['pagesize'] = isset($param['pagesize']) && (int)$param['pagesize'] > 0 ? (int)$param['pagesize'] : 0;

    if($param['page'] == 0){
        json(['code' => 4000, 'msg' => lang('code_4000')])->send();exit();
    }

    if($param['pagesize'] == 0){
        json(['code' => 4000, 'msg' => lang('code_4000')])->send();exit();
    }

    return $param;
}


function getDecryptToken($token){
    if(empty($token)){
        return '';
    }
    return (new \app\index\service\EncryptService())->dataDecrypt($token);
}

function getDecryptData($data){
    if(!is_array($data) || !isset($data['data'])){
        return [];
    }
    return json_decode((new \app\index\service\EncryptService())->dataDecrypt($data['data']), true);
}

function create_random_str($str)
{
    return md5(uniqid('pmzs') . mt_rand(10000000, 99999999) . $str);
}

/**
 * 检测日期格式是否正确
 * @param $date
 * @param int $type   1 Y-m-d   2 Y-m-d h:i:s  3 Y-m
 * @param bool $empty  true时 $date不能为空
 * @return bool
 */
function check_date($date, $type=1, $empty=true){
    if($empty === false){
        if(empty($date)){
            return true;
        }
    }
//    $date = str_replace("/", "-", $date);

    $reg = [
        1 => "/^\d{4}-\d{2}-\d{2}$/",
        2 => "/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/",
        3 => "/^\d{4}-\d{2}$/"
    ];

    if(!preg_match($reg[$type],$date)){
        return false;
    }

    if($type == 1){
        $date_arr = explode("-", $date);
        if((int)$date_arr[0] > 2099 || (int)$date_arr[1] > 12 || (int)$date_arr[2] > 31){
            return false;
        }
    }elseif($type == 2){
        $date_arr = explode(" ", $date);
        $date_ymd_arr = explode("-",$date_arr[0]);
        $date_his_arr = explode(":",$date_arr[1]);
        if((int)$date_ymd_arr[0] > 2099 || (int)$date_ymd_arr[1] > 12 || (int)$date_ymd_arr[2] > 31){
            return false;
        }
        if((int)$date_his_arr[0] > 23 || (int)$date_his_arr[1] > 59 || (int)$date_his_arr[2] > 59){
            return false;
        }
    }elseif ($type == 3){
        $date_arr = explode("-", $date);
        if((int)$date_arr[0] > 2099 || (int)$date_arr[1] > 12){
            return false;
        }
    }

    return true;
}




// 层级处理
function get_tree_data($array, $id = 'id' , $pid = 0, $level = 1)
{
    static $list = [];
    foreach ($array as $v) {
        if ($v['pid'] == $pid) {
            $v['level'] = $level;
            $list[] = $v;
            get_tree_data($array, $id, $v[$id],$level + 1);
        }
    }
    return $list;
}


/**
 * 分类递归
 * @param $data
 * @param int $pid
 * @param string $pk
 * @param string $pid_name
 * @return array
 */
function array2tree(&$array, $pk = 'id', $pid_name = 'pid', $child_key_name = 'children', $sort= '')
{
    $counter = array_children_count($array, $pid_name);
    if (!isset($counter[0]) || $counter[0] == 0) {
        return $array;
    }
    $tree = [];
    while (isset($counter[0]) && $counter[0] > 0) {
        $temp = array_shift($array);

        if (isset($counter[$temp[$pk]]) && $counter[$temp[$pk]] > 0) {
            array_push($array, $temp);
        } else {
            if ($temp[$pid_name] == 0) {
                $tree[] = $temp;
            } else {
                $array = array_child_append($array,$pk, $temp[$pid_name], $temp, $child_key_name, $sort);
            }
        }
        $counter = array_children_count($array, $pid_name);
    }

    return $tree;
}

/**
 * 子元素计数器
 * @param array $array
 * @param int $pid
 * @return array
 */
function array_children_count($array, $pid)
{
    $counter = [];
    foreach ($array as $item) {
        $count = isset($counter[$item[$pid]]) ? $counter[$item[$pid]] : 0;
        $count++;
        $counter[$item[$pid]] = $count;
    }

    return $counter;
}

/**
 * 把元素插入到对应的父元素$child_key_name字段
 * @param        $parent
 * @param        $pid
 * @param        $child
 * @param string $child_key_name 子元素键名
 * @return mixed
 */
function array_child_append($parent, $pk, $pid, $child, $child_key_name, $sort)
{
    foreach ($parent as &$item) {
        if ($item[$pk] == $pid) {
            if (!isset($item[$child_key_name]))
                $item[$child_key_name] = [];
            $item[$child_key_name][] = $child;

            if($sort){
                $sarr = array_column($item[$child_key_name],$sort);
                array_multisort($sarr,SORT_ASC,$item[$child_key_name]);
            }
            //$item[$child_key_name][$child['sort']] = $child;
        }
    }

    return $parent;
}


// 创建借证编号
function created_borrow_num()
{
    return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}

function date_is_empty($date){
    if($date == '0000-00-00' || $date == '' || $date == null){
        return true;
    }
    return false;
}

/**
 * 检查手机号
 * @param $value
 * @return bool
 */
function check_phone($value)
{
    if (strlen($value) != 11) {
        return false;
    }
    $res = preg_match("/^[1][3,4,5,6,7,8,9][0-9]{9}$/", $value, $matches);
    if (!$res) {
        return false;
    }
    return true;
}

/**
 * 获取性别
 * @param $idcard
 * @return string
 */
function check_sex_by_idcard($idcard){
    $num = substr($idcard,-2,1);
    if(($num%2) == 1){
        return '男';
    }
    return '女';
}
function check_birdt_by_idcard ($idcard){
    $date = substr($idcard, 6, 8);
    $birthday = substr($date,0,4).'-'. substr($date,4,2).'-'. substr($date,6,2);
    return $birthday;
}


function encrypt($string,$operation,$key='')
{
    if($operation=='D'){
        $string = str_replace('000000','/',$string);
    }

    $key=md5($key);
    $key_length=strlen($key);
    $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string;
    $string_length=strlen($string);
    $rndkey=$box=array();
    $result='';
    for($i=0;$i<=255;$i++)
    {
        $rndkey[$i]=ord($key[$i%$key_length]);
        $box[$i]=$i;
    }
    for($j=$i=0;$i<256;$i++)
    {
        $j=($j+$box[$i]+$rndkey[$i])%256;
        $tmp=$box[$i];
        $box[$i]=$box[$j];
        $box[$j]=$tmp;
    }
    for($a=$j=$i=0;$i<$string_length;$i++)
    {
        $a=($a+1)%256;
        $j=($j+$box[$a])%256;
        $tmp=$box[$a];
        $box[$a]=$box[$j];
        $box[$j]=$tmp;
        $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));
    }
    if($operation=='D')
    {
        if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8))
        {
            return substr($result,8);
        }
        else
        {
            return'';
        }
    }
    else
    {
        $str = str_replace('=','',base64_encode($result));
        $str = str_replace('/','000000',$str);
        return $str;
    }
}


/**
 * 计算两个日期相隔天数
 * @param $day1
 * @param $day2
 * @return float|int
 */
function count_days($a,$b){
    $time1 = strtotime($a);
    $time2 = strtotime($b);
    if($time1 > $time2){
        return 0;
    }
    $n = ceil(($time2- $time1)/24/60/60) + 1;
    return round(abs($n));
}

function watermark($ori_img,$new_img,$word=''){
    $original = getimagesize($ori_img);	//得到图片的信息，可以print_r($original)发现它就是一个数组
    $s_original = imgCreateFrom($ori_img, $original[2]);	//$original[2]是图片类型，其中1表示gif、2表示jpg、3表示png
    // 图片的宽高
    $imgWidth = imagesx($s_original);
    $imgHeight = imagesy($s_original);

    $font_size = get_water_fontsize($imgWidth, 10, $word);
    $fontarea = imagettfbbox($font_size, 0 , 'C:/Windows/Fonts/simfang.ttf', $word);


    $fontWidth = $fontarea[2] - $fontarea[0];
    $fontHeight = $fontarea[1] - $fontarea[7];

    //(5)计算字符串的起始坐标
//    $posX = $imgWidth/2-$fontWidth/2;
//    $poxY = $imgHeight/2-$fontHeight/2;

    $xie = (hypot($imgWidth, $imgHeight)-hypot($fontWidth, $fontHeight))/2;
    $posX = $imgWidth*$xie/(hypot($imgWidth, $imgHeight));
    $poxY = $imgHeight*$xie/(hypot($imgWidth, $imgHeight)) + $fontHeight/2;
    if($posX < 0) {
        $posX = 10;
    }
    if($poxY < 0) {
        $poxY = 10;
    }

    //文字的倾斜度
    $tilt = -rad2deg(atan($imgHeight/$imgWidth));
    $color = imagecolorallocate($s_original,210,210,210);// 为一幅图像分配颜色 255,0,0表示红色

    //打水印
    imagettftext($s_original, $font_size, $tilt,  $posX, $poxY, $color, 'C:/Windows/Fonts/simfang.ttf', $word);

    imagejpeg($s_original, $new_img);	//生成新的图片(jpg格式)，如果用imagepng可以生成png格式
}
function get_water_fontsize($imgWidth, $font_size, $word){
    $fontarea = imagettfbbox($font_size, 0 , 'C:/Windows/Fonts/simfang.ttf', $word);
    $fontWidth = $fontarea[2] - $fontarea[0];
    if($fontWidth < $imgWidth*0.7){
        return get_water_fontsize($imgWidth, $font_size+1, $word);
    }
    return $font_size-1;
}
//根据文件类型 创建一个新图象
function imgCreateFrom($img_src, $val){
    @ini_set("memory_limit","1280M");
    switch($val){
        case 1 :
            $img = imagecreatefromgif($img_src);
            break;
        case 2 :
            try{
                $img = imagecreatefromjpeg($img_src);
            }catch (Exception $e){
                echo $e->getMessage();
                halt($e);
            }
            break;
        case 3 :
            $img = imagecreatefrompng($img_src);
            break;
    }
    return $img;
}

/**
 * 删除文件夹和下面的文件
 * @param $dir
 * @return bool
 */
function deldir_f($dir) {
    //先删除目录下的文件：
    $dh=opendir($dir);
    while ($file=readdir($dh)) {
        if($file!="." && $file!="..") {
            $fullpath=$dir."/".$file;
            if(!is_dir($fullpath)) {
                unlink($fullpath);
            } else {
                deldir($fullpath);
            }
        }
    }

    closedir($dh);
    //删除当前文件夹：
    if(rmdir($dir)) {
        return true;
    } else {
        return false;
    }
}

function get_week_arr($time=0, $format = "Y-m-d"){
    if(!$time){
        $time = time();
    }
    $week = date('w', $time);
    $weekname = array('星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日');
    //星期日排到末位
    if (empty($week)) {
        $week = 7;
    }
    for ($i = 0; $i <= 6; $i++) {
        $currDay = $i+1-$week;
        $data[$i]['date'] = date($format, strtotime("+{$currDay} days", $time));
        $data[$i]['week'] = $weekname[$i];
    }
    return $data;
}

/**
 * 获取时间段的天数
 * @param $startdt
 * @param $enddt
 */
function get_time_slot_days($startdt,$enddt){
    $stimestamp = strtotime($startdt);
    $etimestamp = strtotime($enddt);
    $days = ($etimestamp-$stimestamp)/86400+1;
    return $days;
}


//发送验证码
function send_message($template, $tel, $msg)
{
    require_once '../vendor/Alimsg/api_sdk/Sms.php';
    $sms = new \Sms;
    $data = [
        'sign' => \think\facade\Config::get('service.sms.sign'),
        'template' => $template,
        'phone' => $tel,
        'msg' => $msg,
    ];
    $return = $sms->sendSms($data);
    return $return;
}




function getDirContent($path){
    if(!is_dir($path)){
        return false;
    }
    $arr = [];
    $data = scandir($path);
    foreach ($data as $value){
        if($value != '.' && $value != '..'){
            $arr[] = $value;
        }
    }
    return $arr;
}





function deldir($path){
    if(is_dir($path)){
        $p = scandir($path);
        foreach($p as $val){
            if($val !="." && $val !=".."){
                if(is_dir($path.$val)){
                    deldir($path.$val.'/');
                    @rmdir($path.$val.'/');
                }else{
                    unlink($path.$val);
                }
            }
        }
    }
}

function maths($exp){
    $arr_exp = [];
    for($i=0;$i<strlen($exp);$i++){
        if($exp[$i]=='+' || $exp[$i]=='-' || $exp[$i]=='*' || $exp[$i]=='/' || $exp[$i]=='(' || $exp[$i]==')'){
            $arr_exp[] = $exp[$i];
        }else{
            if(end($arr_exp)=='+' || end($arr_exp)=='-' || end($arr_exp)=='*' || end($arr_exp)=='/' || end($arr_exp)=='(' || end($arr_exp)==')' || end($arr_exp)==''){
                $arr_exp[] = $exp[$i];
            }else{
                $arr_exp[key($arr_exp)] = end($arr_exp).$exp[$i];
            }
        }
    }
    $result = calculator( array_reverse($arr_exp) );
    return $result;
}
function calculator( $exp ){
    $arr_n  = [];
    $arr_op = [];
    while( ($s = array_pop( $exp )) != '' ){
        if( $s == '(' ){
            $temp = [];
            $quote = 1;
            $endquote = 0;
            while( ($t = array_pop($exp)) != '' ){
                if( $t == '(' ){
                    $quote++;
                }
                if( $t == ')' ){
                    $endquote++;
                    if( $quote == $endquote ){
                        break;
                    }
                }
                array_push($temp, $t);
            }
            $temp = array_reverse($temp);
            array_push($arr_n, calculator($temp) );
        }else if( $s == '*' || $s == '/'){
            $n2 = array_pop($exp);
            if( $n2 == '(' ){
                $temp = array();
                $quote = 1;
                $endquote = 0;
                while( ($t = array_pop($exp)) != '' ){
                    if( $t == '(' ){
                        $quote++;
                    }
                    if( $t == ')' ){
                        $endquote++;
                        if( $quote == $endquote )
                            break;
                    }
                    array_push($temp, $t);
                }
                $temp = array_reverse($temp);
                $n2 = calculator($temp);
            }
            $op = $s;
            $n1 = array_pop($arr_n);
            switch ($op) {
                case '+':
                    $result = $n1 + $n2;
                    break;
                case '-':
                    $result = $n1 - $n2;
                    break;
                case '*':
                    $result = $n1 * $n2;
                    break;
                case '/':
                    $result = $n1 / $n2;
                    break;
            }
            array_push($arr_n, $result);
        }else if( $s == '+' || $s == '-' ){
            array_push($arr_op, $s);
        }else{
            array_push($arr_n, $s);
        }
    }
    $n2 = array_pop($arr_n);
    while( ($op = array_pop($arr_op)) != '' ){
        $n1 = array_pop($arr_n);
        switch ($op) {
            case '+':
                $n2 = $n1 + $n2;
                break;
            case '-':
                $n2 = $n1 - $n2;
                break;
            case '*':
                $n2 = $n1 * $n2;
                break;
            case '/':
                $n2 = $n1 / $n2;
                break;
        }
    }
    return $n2;
}


function search_arr2_min($arr,$field){
    if(!is_array($arr) || !$field){
        return false;
    }

    $temp = [];
    foreach ($arr as $key=>$val) {
        $temp[] = $val[$field];
    }
    if(count($temp) < 1){
        return '';
    }
    return min($temp);
}

function curl_get_sub($url){
    $ch = curl_init();

    //设置选项，包括URL
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//绕过ssl验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    //执行并获取HTML文档内容
    $output = curl_exec($ch);
    //释放curl句柄
    curl_close($ch);
    return json_decode($output,true);
}


function curl_post_sub($url, $data){
    $ch = curl_init();
    //$header = "Accept-Charset: utf-8";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    //curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    //curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $tmpInfo = curl_exec($ch);
    if (curl_errno($ch)) {
        curl_close( $ch );
        return json_decode($ch,true);
    }else{
        curl_close( $ch );
        return json_decode($tmpInfo,true);
    }

}
